<template>
  <div class="max-w-6xl mx-auto p-6 min-h-screen bg-gradient-to-br from-slate-50 to-emerald-50">
    <!-- 页面标题 -->
    <div class="text-center mb-8 p-8 bg-white rounded-2xl shadow-lg">
      <h2 class="flex items-center justify-center gap-3 text-3xl font-semibold text-gray-800 mb-2">
        <n-icon class="text-4xl text-emerald-500" :component="DocumentIcon" />
        积极分子考察表编辑
      </h2>
      <p class="text-gray-600">请完善积极分子考察相关信息和培养记录</p>
    </div>

    <!-- 提示信息模块 -->
    <div class="mb-6 bg-gradient-to-r from-emerald-50 to-green-50 border border-emerald-200 rounded-2xl p-6 shadow-sm">
      <div class="flex items-center gap-3 mb-4">
        <n-icon class="text-2xl text-emerald-600" :component="InfoIcon" />
        <h3 class="text-lg font-semibold text-emerald-800">重要提示信息</h3>
      </div>
      <div class="space-y-2">
        <div v-for="(tip, index) in tipMessages" :key="index" class="flex items-start gap-3 text-sm text-emerald-700">
          <div class="flex-shrink-0 w-1.5 h-1.5 bg-emerald-500 rounded-full mt-2"></div>
          <span>{{ tip }}</span>
        </div>
      </div>
    </div>

    <!-- 基本考察信息和培训信息卡片 -->
    <n-card class="mb-6 rounded-2xl border-0 shadow-lg bg-white overflow-hidden" title="" :bordered="false">
      <template #header>
        <div class="flex items-center justify-between">
          <div class="flex items-center gap-3 py-2">
            <n-icon class="text-xl text-emerald-500" :component="UserIcon" />
            <span class="text-lg font-semibold text-gray-800">基本考察信息</span>
          </div>
          <n-button 
            type="primary" 
            @click="saveBasicInfo"
            :loading="basicInfoLoading"
            :disabled="!basicInfoChanged"
            class="rounded-lg"
          >
            <template #icon>
              <n-icon :component="SaveIcon" />
            </template>
            保存基本信息
          </n-button>
        </div>
      </template>
      
      <n-form ref="basicFormRef" :model="basicInfo" label-placement="top" label-align="left" label-width="auto">
        <!-- 基本考察信息区域 -->
        <div class="mb-6">
          <h4 class="text-md font-medium text-gray-700 mb-4 flex items-center gap-2">
            <n-icon class="text-lg text-emerald-500" :component="UserIcon" />
            考察基础信息
          </h4>
          <n-grid :cols="24" :x-gap="24" :y-gap="5">
            <!-- 第一行：列为积极分子时间、主要表现支部书记签名 -->
            <n-form-item-gi :span="12" label="列为积极分子时间" path="activistDesignationDate">
              <n-date-picker 
                v-model:formatted-value="basicInfo.activistDesignationDate" 
                type="date" 
                value-format="yyyy-MM-dd" 
                style="width: 100%" 
                placeholder="选择列为积极分子时间"
                class="rounded-lg"
              />
            </n-form-item-gi>
            <n-form-item-gi :span="12" label="主要表现支部书记签名" path="secretarySignature">
              <n-input
                v-model:value="basicInfo.secretarySignature"
                placeholder="请输入党支部书记签名"
                class="rounded-lg"
              />
            </n-form-item-gi>

            <!-- 第二行：党支部书记签名日期、支委会意见日期 -->
            <n-form-item-gi :span="12" label="党支部书记签名日期" path="secretarySignatureDate">
              <n-date-picker
                v-model:formatted-value="basicInfo.secretarySignatureDate"
                type="date"
                value-format="yyyy-MM-dd"
                style="width: 100%"
                placeholder="选择党支部书记签名日期"
                class="rounded-lg"
              />
            </n-form-item-gi>
            <n-form-item-gi :span="12" label="支委会意见日期" path="committeeOpinionDate">
              <n-date-picker
                v-model:formatted-value="basicInfo.committeeOpinionDate"
                type="date"
                value-format="yyyy-MM-dd"
                style="width: 100%"
                placeholder="选择支委会意见日期"
                class="rounded-lg"
              />
            </n-form-item-gi>

            <!-- 第三行：支部书记签名、群众座谈组织委员签名 -->
            <n-form-item-gi :span="12" label="支部书记签名" path="committeeSignature">
              <n-input
                v-model:value="basicInfo.committeeSignature"
                placeholder="请输入支部书记签名"
                class="rounded-lg"
              />
            </n-form-item-gi>

            <!-- 第四行：群众座谈组织委员签名、群众座谈意见落款日期 -->
            <n-form-item-gi :span="12" label="群众座谈组织委员签名" path="massDiscussionOrganizerSignature">
              <n-input 
                v-model:value="basicInfo.massDiscussionOrganizerSignature" 
                placeholder="请输入组织委员签名"
                class="rounded-lg"
              />
            </n-form-item-gi>
            <n-form-item-gi :span="12" label="群众座谈意见落款日期" path="massDiscussionDate">
              <n-date-picker 
                v-model:formatted-value="basicInfo.massDiscussionDate" 
                type="date" 
                value-format="yyyy-MM-dd" 
                style="width: 100%" 
                placeholder="选择群众座谈意见落款日期"
                class="rounded-lg"
              />
            </n-form-item-gi>
          </n-grid>
        </div>

        <!-- 培训信息区域 -->
        <div>
          <h4 class="text-md font-medium text-gray-700 mb-4 flex items-center gap-2">
            <n-icon class="text-lg text-emerald-600" :component="SchoolIcon" />
            培训信息
          </h4>
          <n-grid :cols="24" :x-gap="24" :y-gap="5">
            <!-- 第一行：教育培训开始日期、教育培训结束日期 -->
            <n-form-item-gi :span="12" label="教育培训开始日期" path="trainingStartDate">
              <n-date-picker 
                v-model:formatted-value="basicInfo.trainingStartDate" 
                type="date" 
                value-format="yyyy-MM-dd" 
                style="width: 100%" 
                placeholder="选择教育培训开始日期"
                class="rounded-lg"
              />
            </n-form-item-gi>
            <n-form-item-gi :span="12" label="教育培训结束日期" path="trainingEndDate">
              <n-date-picker 
                v-model:formatted-value="basicInfo.trainingEndDate" 
                type="date" 
                value-format="yyyy-MM-dd" 
                style="width: 100%" 
                placeholder="选择教育培训结束日期"
                class="rounded-lg"
              />
            </n-form-item-gi>

            <!-- 第二行：短期集中培训开始日期、短期集中培训结束日期 -->
            <n-form-item-gi :span="12" label="短期集中培训开始日期" path="developmentTrainingStartDate">
              <n-date-picker 
                v-model:formatted-value="basicInfo.developmentTrainingStartDate" 
                type="date" 
                value-format="yyyy-MM-dd" 
                style="width: 100%" 
                placeholder="选择短期集中培训开始日期"
                class="rounded-lg"
              />
            </n-form-item-gi>
            <n-form-item-gi :span="12" label="短期集中培训结束日期" path="developmentTrainingEndDate">
              <n-date-picker 
                v-model:formatted-value="basicInfo.developmentTrainingEndDate" 
                type="date" 
                value-format="yyyy-MM-dd" 
                style="width: 100%" 
                placeholder="选择短期集中培训结束日期"
                class="rounded-lg"
              />
            </n-form-item-gi>
          </n-grid>
        </div>
      </n-form>
    </n-card>

    <!-- 培养人列表卡片 -->
    <n-card class="mb-6 rounded-2xl border-0 shadow-lg bg-white overflow-hidden" title="" :bordered="false">
      <template #header>
        <div class="flex items-center justify-between">
          <div class="flex items-center gap-3 py-2">
            <n-icon class="text-xl text-emerald-600" :component="PeopleIcon" />
            <span class="text-lg font-semibold text-gray-800">培养人列表</span>
          </div>
          <n-button 
            type="primary" 
            @click="addMentor"
            class="rounded-lg"
            ghost
          >
            <template #icon>
              <n-icon :component="PlusIcon" />
            </template>
            新增培养人
          </n-button>
        </div>
      </template>

      <div class="mb-3">
        <n-empty 
          v-if="!mentorList || mentorList.length === 0"
          description="暂无培养人记录"
          class="py-8 text-slate-500"
        >
          <template #icon>
            <n-icon :component="PeopleIcon" class="text-3xl text-slate-400" />
          </template>
        </n-empty>
        
        <div v-for="(mentor, index) in mentorList" :key="mentor.tempId || mentor.id || index" class="bg-emerald-50 border border-emerald-200 rounded-xl p-4 mb-3 transition-all duration-300 hover:shadow-md hover:-translate-y-0.5">
          <div class="flex justify-between items-center mb-3">
            <div class="flex items-center gap-3">
              <span class="flex items-center justify-center w-6 h-6 bg-emerald-500 text-white rounded-full text-xs font-semibold">{{ index + 1 }}</span>
              <span v-if="mentor.isNew" class="px-2 py-1 bg-green-100 text-green-600 text-xs rounded-full">新增</span>
            </div>
            <div class="flex gap-2">
              <n-button 
                type="primary" 
                @click="saveMentor(mentor, index)"
                :loading="mentorSaveLoading[index]"
                :disabled="!mentorChanged[index]"
                class="rounded-lg"
                size="small"
              >
                <template #icon>
                  <n-icon :component="SaveIcon" />
                </template>
                保存
              </n-button>
              <n-button 
                text 
                type="error" 
                @click="deleteMentor(mentor, index)"
                :loading="mentorDeleteLoading[index]"
                class="text-gray-500 hover:text-gray-700 hover:bg-gray-100 transition-all duration-300"
                size="small"
              >
                <template #icon>
                  <n-icon :component="DeleteIcon" />
                </template>
                {{ mentor.isNew ? '取消' : '删除' }}
              </n-button>
            </div>
          </div>
          <n-grid :cols="12" :x-gap="12" :y-gap="6">
            <n-gi :span="6">
              <n-form-item label="姓名" label-placement="top" :label-style="{ fontSize: '13px' }">
                <n-input 
                  v-model:value="mentor.mentorName" 
                  placeholder="请输入培养人姓名"
                  class="rounded-lg"
                  size="small"
                />
              </n-form-item>
            </n-gi>
            <n-gi :span="6">
              <n-form-item label="入党时间" label-placement="top" :label-style="{ fontSize: '13px' }">
                <n-date-picker 
                  v-model:formatted-value="mentor.joinPartyDate" 
                  value-format="yyyy-MM-dd" 
                  type="date" 
                  placeholder="选择入党时间"
                  style="width: 100%"
                  class="rounded-lg"
                  size="small"
                />
              </n-form-item>
            </n-gi>
            <n-gi :span="6">
              <n-form-item label="一起工作时间" label-placement="top" :label-style="{ fontSize: '13px' }">
                <n-date-picker 
                  v-model:formatted-value="mentor.workTogetherStart" 
                  value-format="yyyy-MM-dd" 
                  type="date" 
                  placeholder="选择一起工作时间"
                  style="width: 100%"
                  class="rounded-lg"
                  size="small"
                />
              </n-form-item>
            </n-gi>
            <n-gi :span="6">
              <n-form-item label="何时起做培养人" label-placement="top" :label-style="{ fontSize: '13px' }">
                <n-date-picker 
                  v-model:formatted-value="mentor.mentorStartDate" 
                  value-format="yyyy-MM-dd" 
                  type="date" 
                  placeholder="选择开始做培养人时间"
                  style="width: 100%"
                  class="rounded-lg"
                  size="small"
                />
              </n-form-item>
            </n-gi>
          </n-grid>
        </div>
      </div>
    </n-card>

    <!-- 培养考察写实列表卡片 -->
    <n-card class="mb-6 rounded-2xl border-0 shadow-lg bg-white overflow-hidden" title="" :bordered="false">
      <template #header>
        <div class="flex items-center justify-between">
          <div class="flex items-center gap-3 py-2">
            <n-icon class="text-xl text-emerald-600" :component="ClipboardIcon" />
            <span class="text-lg font-semibold text-gray-800">培养考察写实列表</span>
          </div>
          <n-button 
            type="info" 
            @click="addAssessmentRecord"
            class="rounded-lg"
            ghost
          >
            <template #icon>
              <n-icon :component="PlusIcon" />
            </template>
            新增培养考察写实
          </n-button>
        </div>
      </template>

      <div class="mb-3">
        <n-empty 
          v-if="!assessmentRecords || assessmentRecords.length === 0"
          description="暂无培养考察写实记录"
          class="py-8 text-slate-500"
        >
          <template #icon>
            <n-icon :component="ClipboardIcon" class="text-3xl text-slate-400" />
          </template>
        </n-empty>
        
        <div v-for="(record, index) in assessmentRecords" :key="record.tempId || record.id || index" class="bg-blue-50 border border-blue-200 rounded-xl p-4 mb-3 transition-all duration-300 hover:shadow-md hover:-translate-y-0.5">
          <div class="flex justify-between items-center mb-3">
            <div class="flex items-center gap-3">
              <span class="flex items-center justify-center w-6 h-6 bg-blue-500 text-white rounded-full text-xs font-semibold">{{ index + 1 }}</span>
              <span v-if="record.isNew" class="px-2 py-1 bg-green-100 text-green-600 text-xs rounded-full">新增</span>
            </div>
            <div class="flex gap-2">
              <n-button 
                type="info" 
                @click="saveAssessmentRecord(record, index)"
                :loading="recordSaveLoading[index]"
                :disabled="!recordChanged[index]"
                class="rounded-lg"
                size="small"
              >
                <template #icon>
                  <n-icon :component="SaveIcon" />
                </template>
                保存
              </n-button>
              <n-button 
                text 
                type="error" 
                @click="deleteAssessmentRecord(record, index)"
                :loading="recordDeleteLoading[index]"
                class="text-gray-500 hover:text-gray-700 hover:bg-gray-100 transition-all duration-300"
                size="small"
              >
                <template #icon>
                  <n-icon :component="DeleteIcon" />
                </template>
                {{ record.isNew ? '取消' : '删除' }}
              </n-button>
            </div>
          </div>
          <n-grid :cols="15" :x-gap="12" :y-gap="6">
            <n-gi :span="3">
              <n-form-item label="培养联系人1姓名" label-placement="top" :label-style="{ fontSize: '13px' }">
                <n-input 
                  v-model:value="record.mentor1Name" 
                  placeholder="请输入培养联系人1姓名"
                  class="rounded-lg"
                  size="small"
                />
              </n-form-item>
            </n-gi>
            <n-gi :span="3">
              <n-form-item label="培养联系人2姓名" label-placement="top" :label-style="{ fontSize: '13px' }">
                <n-input 
                  v-model:value="record.mentor2Name" 
                  placeholder="请输入培养联系人2姓名"
                  class="rounded-lg"
                  size="small"
                />
              </n-form-item>
            </n-gi>
            <n-gi :span="3">
              <n-form-item label="培养联系人意见时间" label-placement="top" :label-style="{ fontSize: '13px' }">
                <n-date-picker 
                  v-model:formatted-value="record.mentorOpinionDate" 
                  value-format="yyyy-MM-dd" 
                  type="date" 
                  placeholder="选择意见时间"
                  style="width: 100%"
                  class="rounded-lg"
                  size="small"
                />
              </n-form-item>
            </n-gi>
            <n-gi :span="3">
              <n-form-item label="党支部书记姓名" label-placement="top" :label-style="{ fontSize: '13px' }">
                <n-input 
                  v-model:value="record.branchSecretaryName" 
                  placeholder="请输入党支部书记姓名"
                  class="rounded-lg"
                  size="small"
                />
              </n-form-item>
            </n-gi>
            <n-gi :span="3">
              <n-form-item label="党支部意见落款日期" label-placement="top" :label-style="{ fontSize: '13px' }">
                <n-date-picker 
                  v-model:formatted-value="record.branchOpinionDate" 
                  value-format="yyyy-MM-dd" 
                  type="date" 
                  placeholder="选择落款日期"
                  style="width: 100%"
                  class="rounded-lg"
                  size="small"
                />
              </n-form-item>
            </n-gi>
          </n-grid>
        </div>
      </div>
    </n-card>
  </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue'
import {
  NForm, NFormItem, NFormItemGi, NGrid, NInput, NDatePicker, NButton, NGi, NCard, NIcon, NEmpty
} from 'naive-ui'
import { 
  Document as DocumentIcon,
  Person as UserIcon,
  School as SchoolIcon,
  People as PeopleIcon,
  Clipboard as ClipboardIcon,
  Add as PlusIcon,
  TrashOutline as DeleteIcon,
  InformationCircle as InfoIcon,
  Save as SaveIcon
} from '@vicons/ionicons5'
import { cloneDeep } from 'lodash-es';

const props = defineProps({
  member: {
    type: Object,
    required: true
  }
})

const emit = defineEmits([
  'save-basic-info',
  'save-mentor',
  'delete-mentor',
  'save-assessment-record',
  'delete-assessment-record'
])

const basicFormRef = ref(null)

// 安全处理日期字段的函数
const safeDateValue = (dateStr) => {
  if (!dateStr || dateStr === '' || dateStr === 'null' || dateStr === 'undefined') {
    return null
  }
  const date = new Date(dateStr)
  if (isNaN(date.getTime())) {
    return null
  }
  return dateStr
}

// 基本信息
const basicInfo = ref({})
const originalBasicInfo = ref({})
const basicInfoChanged = ref(false)

// 列表数据
const mentorList = ref([])
const assessmentRecords = ref([])

// 原始数据副本，用于比较变化
const originalMentorList = ref([])
const originalAssessmentRecords = ref([])

// 变化状态
const mentorChanged = ref({})
const recordChanged = ref({})

// 加载状态
const basicInfoLoading = ref(false)
const mentorSaveLoading = ref({})
const mentorDeleteLoading = ref({})
const recordSaveLoading = ref({})
const recordDeleteLoading = ref({})

// 提示信息配置
const tipMessages = ref([])

// 生成唯一临时ID
const generateTempId = () => {
  return `temp_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
}

// 生成提示信息的函数
const generateTipMessages = () => {
  const defaultTips = [
    '培养人至少需要配置两名正式党员作为联系人',
    '培养考察写实需要定期记录，建议每季度至少一次',
    '培训时间安排需要符合党组织的统一部署',
    '各项签名字段请确保签名人身份准确无误',
    '所有日期字段应按照实际时间顺序填写'
  ]
  tipMessages.value = defaultTips
}

// 配置提示信息内容的函数（预留接口）
const configureTipMessages = (messages) => {
  if (Array.isArray(messages)) {
    tipMessages.value = messages
  }
}

// 深度比较对象是否相等
const isEqual = (obj1, obj2) => {
  return JSON.stringify(obj1) === JSON.stringify(obj2)
}

// 安全处理对象中的所有日期字段
const safeProcessDates = (obj) => {
  if (!obj) return obj
  
  const dateFields = [
    'activistDesignationDate', 'secretarySignatureDate', 'trainingStartDate', 'trainingEndDate',
    'developmentTrainingStartDate', 'developmentTrainingEndDate',
    'committeeOpinionDate', 'massDiscussionDate'
  ]
  
  dateFields.forEach(field => {
    if (obj.hasOwnProperty(field)) {
      obj[field] = safeDateValue(obj[field])
    }
  })
  
  return obj
}

// 初始化数据
const initData = () => {
  if (props.member) {
    // 确保activistAssessment对象存在
    const activistAssessment = props.member.activistAssessment || {}
    
    // 提取基本信息（考察信息+培训信息）
    const basicData = {
      activistDesignationDate: safeDateValue(activistAssessment.activistDesignationDate),
      secretarySignature: activistAssessment.secretarySignature || '',
      secretarySignatureDate: safeDateValue(activistAssessment.secretarySignatureDate),
      committeeOpinionDate: safeDateValue(activistAssessment.committeeOpinionDate),
      committeeSignature: activistAssessment.committeeSignature || '',
      massDiscussionOrganizerSignature: activistAssessment.massDiscussionOrganizerSignature || '',
      massDiscussionDate: safeDateValue(activistAssessment.massDiscussionDate),
      trainingStartDate: safeDateValue(activistAssessment.trainingStartDate),
      trainingEndDate: safeDateValue(activistAssessment.trainingEndDate),
      developmentTrainingStartDate: safeDateValue(activistAssessment.developmentTrainingStartDate),
      developmentTrainingEndDate: safeDateValue(activistAssessment.developmentTrainingEndDate)
    }
    
    basicInfo.value = cloneDeep(basicData)
    originalBasicInfo.value = cloneDeep(basicData)
    
    // 初始化列表数据并处理日期字段
    const mentorListData = (activistAssessment.mentorList || []).map(mentor => ({
      ...mentor,
      joinPartyDate: safeDateValue(mentor.joinPartyDate),
      workTogetherStart: safeDateValue(mentor.workTogetherStart),
      mentorStartDate: safeDateValue(mentor.mentorStartDate)
    }))
    
    const assessmentRecordsData = (activistAssessment.assessmentRecords || []).map(record => ({
      ...record,
      mentorOpinionDate: safeDateValue(record.mentorOpinionDate),
      branchOpinionDate: safeDateValue(record.branchOpinionDate)
    }))
    
    mentorList.value = cloneDeep(mentorListData)
    assessmentRecords.value = cloneDeep(assessmentRecordsData)
    
    // 保存原始数据
    originalMentorList.value = cloneDeep(mentorListData)
    originalAssessmentRecords.value = cloneDeep(assessmentRecordsData)
  }
}

// 监听基本信息变化
watch(basicInfo, (newVal) => {
  basicInfoChanged.value = !isEqual(newVal, originalBasicInfo.value)
}, { deep: true })

// 监听培养人列表变化
watch(mentorList, (newList) => {
  newList.forEach((item, index) => {
    const original = originalMentorList.value.find(orig => orig.id === item.id)
    if (item.isNew || !original) {
      // 新增的记录，检查是否有内容变化
      const emptyItem = {
        mentorName: '',
        joinPartyDate: null,
        workTogetherStart: null,
        mentorStartDate: null
      }
      mentorChanged.value[index] = !isEqual({
        mentorName: item.mentorName,
        joinPartyDate: item.joinPartyDate,
        workTogetherStart: item.workTogetherStart,
        mentorStartDate: item.mentorStartDate
      }, emptyItem)
    } else {
      // 现有记录，与原始数据比较
      mentorChanged.value[index] = !isEqual({
        mentorName: item.mentorName,
        joinPartyDate: item.joinPartyDate,
        workTogetherStart: item.workTogetherStart,
        mentorStartDate: item.mentorStartDate
      }, {
        mentorName: original.mentorName,
        joinPartyDate: original.joinPartyDate,
        workTogetherStart: original.workTogetherStart,
        mentorStartDate: original.mentorStartDate
      })
    }
  })
}, { deep: true })

// 监听培养考察写实列表变化
watch(assessmentRecords, (newList) => {
  newList.forEach((item, index) => {
    const original = originalAssessmentRecords.value.find(orig => orig.id === item.id)
    if (item.isNew || !original) {
      // 新增的记录
      const emptyItem = {
        mentor1Name: '',
        mentor2Name: '',
        mentorOpinionDate: null,
        branchSecretaryName: '',
        branchOpinionDate: null
      }
      recordChanged.value[index] = !isEqual({
        mentor1Name: item.mentor1Name,
        mentor2Name: item.mentor2Name,
        mentorOpinionDate: item.mentorOpinionDate,
        branchSecretaryName: item.branchSecretaryName,
        branchOpinionDate: item.branchOpinionDate
      }, emptyItem)
    } else {
      // 现有记录
      recordChanged.value[index] = !isEqual({
        mentor1Name: item.mentor1Name,
        mentor2Name: item.mentor2Name,
        mentorOpinionDate: item.mentorOpinionDate,
        branchSecretaryName: item.branchSecretaryName,
        branchOpinionDate: item.branchOpinionDate
      }, {
        mentor1Name: original.mentor1Name,
        mentor2Name: original.mentor2Name,
        mentorOpinionDate: original.mentorOpinionDate,
        branchSecretaryName: original.branchSecretaryName,
        branchOpinionDate: original.branchOpinionDate
      })
    }
  })
}, { deep: true })

onMounted(() => {
  generateTipMessages()
  initData()
})

watch(() => props.member, () => {
  initData()
}, { deep: true })

// =============== 基本信息操作 ===============
const saveBasicInfo = async () => {
  basicInfoLoading.value = true
  try {
    await emit('save-basic-info', cloneDeep(basicInfo.value))
    // 保存成功后更新原始数据
    originalBasicInfo.value = cloneDeep(basicInfo.value)
    basicInfoChanged.value = false
  } finally {
    basicInfoLoading.value = false
  }
}

// =============== 培养人操作 ===============
const addMentor = () => {
  const tempId = generateTempId()
  const newMentor = {
    tempId,
    isNew: true,
    mentorName: '',
    joinPartyDate: null,
    workTogetherStart: null,
    mentorStartDate: null
  }
  mentorList.value.unshift(newMentor)
}

const saveMentor = async (mentor, index) => {
  mentorSaveLoading.value[index] = true
  try {
    const mentorData = { ...mentor }
    delete mentorData.tempId
    delete mentorData.isNew
    
    if (mentor.isNew) {
      await emit('save-mentor', mentorData, -1) // -1 表示新增
    } else {
      await emit('save-mentor', mentorData, index)
    }
    
    // 保存成功后更新状态
    mentorChanged.value[index] = false
    if (mentor.isNew) {
      mentor.isNew = false
    }
  } finally {
    mentorSaveLoading.value[index] = false
  }
}

const deleteMentor = async (mentor, index) => {
  if (mentor.isNew) {
    // 新增的记录直接移除
    mentorList.value.splice(index, 1)
    return
  }
  
  mentorDeleteLoading.value[index] = true
  try {
    await emit('delete-mentor', mentor, index)
    // 删除成功后从列表中移除
    mentorList.value.splice(index, 1)
  } finally {
    mentorDeleteLoading.value[index] = false
  }
}

// =============== 培养考察写实操作 ===============
const addAssessmentRecord = () => {
  const tempId = generateTempId()
  const newRecord = {
    tempId,
    isNew: true,
    mentor1Name: '',
    mentor2Name: '',
    mentorOpinionDate: null,
    branchSecretaryName: '',
    branchOpinionDate: null
  }
  assessmentRecords.value.unshift(newRecord)
}

const saveAssessmentRecord = async (record, index) => {
  recordSaveLoading.value[index] = true
  try {
    const recordData = { ...record }
    delete recordData.tempId
    delete recordData.isNew
    
    if (record.isNew) {
      await emit('save-assessment-record', recordData, -1) // -1 表示新增
    } else {
      await emit('save-assessment-record', recordData, index)
    }
    
    // 保存成功后更新状态
    recordChanged.value[index] = false
    if (record.isNew) {
      record.isNew = false
    }
  } finally {
    recordSaveLoading.value[index] = false
  }
}

const deleteAssessmentRecord = async (record, index) => {
  if (record.isNew) {
    // 新增的记录直接移除
    assessmentRecords.value.splice(index, 1)
    return
  }
  
  recordDeleteLoading.value[index] = true
  try {
    await emit('delete-assessment-record', record, index)
    // 删除成功后从列表中移除
    assessmentRecords.value.splice(index, 1)
  } finally {
    recordDeleteLoading.value[index] = false
  }
}

// =============== 数据更新方法（父组件调用） ===============
const updateMentorList = (newList) => {
  const processedList = newList.map(mentor => ({
    ...mentor,
    joinPartyDate: safeDateValue(mentor.joinPartyDate),
    workTogetherStart: safeDateValue(mentor.workTogetherStart),
    mentorStartDate: safeDateValue(mentor.mentorStartDate)
  }))
  mentorList.value = cloneDeep(processedList)
  originalMentorList.value = cloneDeep(processedList)
}

const updateAssessmentRecords = (newList) => {
  const processedList = newList.map(record => ({
    ...record,
    mentorOpinionDate: safeDateValue(record.mentorOpinionDate),
    branchOpinionDate: safeDateValue(record.branchOpinionDate)
  }))
  assessmentRecords.value = cloneDeep(processedList)
  originalAssessmentRecords.value = cloneDeep(processedList)
}

// =============== 获取编辑后的数据 ===============
const getEditedData = () => {
  // 返回完整的activistAssessment对象，而不是包装对象
  console.log('ActivistAssessmentEditor - getEditedData called')
  const activistAssessmentData = {
    // 基本信息
    activistDesignationDate: basicInfo.value.activistDesignationDate,
    secretarySignature: basicInfo.value.secretarySignature,
    secretarySignatureDate: basicInfo.value.secretarySignatureDate,
    committeeOpinionDate: basicInfo.value.committeeOpinionDate,
    committeeSignature: basicInfo.value.committeeSignature,
    massDiscussionOrganizerSignature: basicInfo.value.massDiscussionOrganizerSignature,
    massDiscussionDate: basicInfo.value.massDiscussionDate,
    trainingStartDate: basicInfo.value.trainingStartDate,
    trainingEndDate: basicInfo.value.trainingEndDate,
    developmentTrainingStartDate: basicInfo.value.developmentTrainingStartDate,
    developmentTrainingEndDate: basicInfo.value.developmentTrainingEndDate,
    
    // 培养人列表
    mentorList: mentorList.value.map(mentor => {
      const mentorData = { ...mentor }
      delete mentorData.tempId
      delete mentorData.isNew
      return mentorData
    }),
    
    // 培养考察写实列表
    assessmentRecords: assessmentRecords.value.map(record => {
      const recordData = { ...record }
      delete recordData.tempId
      delete recordData.isNew
      return recordData
    })
  }
  console.log('ActivistAssessmentEditor - returning data:', activistAssessmentData)
  return activistAssessmentData
}

defineExpose({
  configureTipMessages,
  updateMentorList,
  updateAssessmentRecords,
  getEditedData
})
</script>